const app = getApp();
Page({
  data: {
    staticImg: app.globalData.staticImg,
    totalPrice: '0.00',
    totalPoint: 0,
    num: '0',
    list : [],
    number:0,
    del:0,
    ed:0,
    indicatorDots: true,
    autoplay: true,
    interval: 2000,
    duration: 1000,
    cartdDan:[]
  },
  onLoad:function(){
    var that = this;
    this.dialog = this.selectComponent("#dialog");
    this.dialog.showDialog();
    //获取手机高度
    that.setData({
      navH: app.globalData.navHeight,
      selectAllStatus:false
    });
    wx.request({
      url: app.globalData.url + 'getUserShoppingCartByUserId',
      data: {
             userId: wx.getStorageSync("userId"),
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method: 'POST',
      success: function (res) {
     
        var data = res.data;
        console.log(data.data);
        if (data.result === 1) {
          that.setData({
            goods: data.data,
          })
          if(data.data.length>0){
            that.setData({
              lipintype: data.data[0].product.type
            })
          }
          
        }
      }
    })
    wx.request({
      url: app.globalData.url + 'getProductUserLikeList',
      data: {
        userId: wx.getStorageSync("userId"),
      },
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        for (var i = 0; i < res.data.data.length; i++) {
          if (res.data.data[i].promotionMsg !=undefined) {
            var arr = res.data.data[i].promotionMsg.split(",");
            res.data.data[i].arr = arr;
          } else {
            res.data.data[i].arr = [];
          }
          if (res.data.data[i].promotionType != undefined) {
            //先按照逗号分割字符串
            let arrycode = res.data.data[i].promotionType.split(",");
            //去重
            arrycode = Array.from(new Set(arrycode));
            //拼接正确的nextOperatorCode
            res.data.data[i].promotionType = arrycode = arrycode.toLocaleString();
            // var promotionType = res.data.data[i].promotionType.split(",");
            // res.data.data[i].promotionType = promotionType;
          } else {
            res.data.data[i].promotionType = [];
          }
        }
        
        that.setData({
          likeList: res.data.data
        })
      }
    })
  },

  onShow: function () {
    var that = this;
    that.onLoad();
    that.setData({
      totalPrice: '0.00',
      totalPoint:0
    })
  },
  
  // 单个选中
  change: function (e) {
    var that = this;
    const index = e.currentTarget.dataset.index; // 获取data- 传进来的index
    var goods = that.data.goods; // 获取购物车列表
    var selectAllStatus = that.data.selectAllStatus; //获取全选状态
    console.info(goods[index]);
    const selected = goods[index].selected; // 获取当前商品的选中状态
    if (that.data.del != 0) {
      goods[index].selected = !selected; // 改变状态
      goods[index]['selected'] = !selected;
    } else {
      if (goods[index].product.valid == true) {
        goods[index].selected = !selected; // 改变状态
        goods[index]['selected'] = !selected;
      }
    } 
    that.data.number=0;
    that.setData({
      number: goods[index].buyCount
    })
   
    //判断有一个没有选中，全选取消
    var j = 0;
    var num = 0;
    for (var i = 0; i < goods.length; i++) {
      if (goods[i].selected == true) {
        num += goods[i].buyCount;
        j++;
        continue;
      } else {
        selectAllStatus = false;
      }
    }
    that.setData({
      number: num
    })
    if (j == goods.length) {
      selectAllStatus = true;
    }
    //如果都选中，全选也选中实现
    that.setData({
      goods: goods,
      selectAllStatus: selectAllStatus,
    });
    
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count(index)
    that.allPoint(index)
  },
  remove: function (array, val) {
       for (var i = 0; i < array.length; i++) {
            if (array[i] == val) {
                array.splice(i, 1);
      }
    }
       return -1;
  },
  // 全选事件
  selectAll: function (e) {
    var that = this;
    var selectAllStatus = that.data.selectAllStatus; // 是否全选状态
    selectAllStatus = !selectAllStatus;
    var goods = that.data.goods;
    //结算组装json 并且改变所有商品状态
    if (that.data.list.length > 0) {
      that.data.list = []
    }
    that.data.number = 0;
    
    for (var i = 0; i < goods.length; i++) {
      if (that.data.del!=0){
        goods[i].selected = selectAllStatus;
        goods[i]['selected'] = selectAllStatus; // 改变所有商品状态
        that.data.number += goods[i].buyCount
      } else {
        if (goods[i].product.valid == true) {
          goods[i].selected = selectAllStatus;
          goods[i]['selected'] = selectAllStatus; // 改变所有商品状态
          that.data.number += goods[i].buyCount
        }

      }
      
    }
    that.setData({
      number: that.data.number
    })
    if (selectAllStatus==false) {
      that.setData({
        number: 0
      })
    }
    var cartId=[];
    for(var i=0; i< goods.length;i++){
      cartId += goods[i].cartId+','
    }
    that.setData({
      selectAllStatus: selectAllStatus,
      goods: goods,
      cartIds: cartId
    });
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count()
    that.allPoint()
  },
  //加法
  addtion: function (e) {
    var that = this
    //得到下标
    var index = e.currentTarget.dataset.index
    //得到点击的值
    var buyCount = e.currentTarget.dataset.num
    
    //把新的值给新的数组
    var newList = that.data.goods

    if (buyCount < newList[index].product.inventoryQuantity) {
      buyCount++;
    }else{
      wx.showToast({
        title: '库存不足',
        icon: "none"
      })
    }
    if (newList[index].product.seckillLimitNum > 0) {
      if (buyCount > newList[index].product.seckillLimitNum) {
        wx.showToast({
          title: '超过限购数量',
          icon: "none"
        })
        return;
      }
    }
    newList[index].buyCount = buyCount
    
    //把新的数组传给前台
    that.setData({
      goods: newList
    })
    wx.request({
      url: app.globalData.url + "modifyShoppingCart",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {
        userId: wx.getStorageSync("userId"),
        productId: e.currentTarget.dataset.productid,
        num: 1
      },
      method: "POST",
      success: function (res) {
        var data = res.data;
        console.log(data)
        if (res.data.result == 0) {
          var newList = that.data.goods;
          newList[index].buyCount = res.data.num
          that.setData({
            goods: newList
          })
          wx.showToast({
            title: '' + res.data.errmsg,
            icon: 'none',
            duration: 2000
          })
        } else {
          that.setData({
            lottery: data.rows
          })

        }
      }
    });
    var num=0;
    for (var i = 0; i < that.data.goods.length; i++) {
      if (that.data.goods[i].selected == true) {
        num += that.data.goods[i].buyCount;
        continue;
      }
    }
    that.setData({
      number: num
    })
    
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count(index)
    that.allPoint(index)
  },
  //减法
  subtraction: function (e) {
    var that = this
    //得到下标
    var index = e.currentTarget.dataset.index
    //得到点击的值
    var buyCount = e.currentTarget.dataset.num
    
    //把新的值给新的数组
    var newList = that.data.goods
    //当1件时，点击移除
    if (buyCount == 1) {
      buyCount == 1
    } else {
      buyCount--
      newList[index].buyCount = buyCount
    }
    //把新的数组传给前台
    that.setData({
      goods: newList
    })
    var num = 0;
    for (var i = 0; i < that.data.goods.length; i++) {
      if (that.data.goods[i].selected == true) {
        num += that.data.goods[i].buyCount;
        continue;
      }
    }
    that.setData({
      number: num
    })
    
    if (e.currentTarget.dataset.num > 1) {
      wx.request({
        url: app.globalData.url + "modifyShoppingCart",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        data: {
          userId: wx.getStorageSync("userId"),
          productId: e.currentTarget.dataset.productid,
          num: -1
        },
        method: "POST",
        success: function (res) {
          var data = res.data;
          console.log(data)
          if (data.result === 1) {
            that.setData({
              lottery: data.rows
            })
          }
        }
      });
    }
    //调用计算数目方法
    that.countNum()
    //计算金额
    that.count(index)
    that.allPoint(index)
  },
  //计算数量
  countNum: function () {
    var that = this
    //遍历数组，把既选中的num加起来
    var newList = that.data.goods
    var allNum = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].selected) {
        allNum += parseInt(newList[i].buyCount)
      }
    }
    that.setData({
      buyCount: allNum
    })
  },
  //计算金额方法
  count: function (index) {
    var that = this
    //选中的订单，数量*价格加起来
    //var price = parseFloat(that.data.goods[index].product.price)
    var newList = that.data.goods
    var newCount = 0.00
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].selected) {
        newCount += newList[i].product.minPrice * newList[i].buyCount
      }
    }
    that.setData({
      // newCount: newCount.toFixed(2),
      totalPrice: newCount.toFixed(2),
    })
  },
  //计算积分方法
  allPoint: function (index) {
    var that = this
    //选中的订单，数量*价格加起来
    //var price = parseFloat(that.data.goods[index].product.price)
    var newList = that.data.goods
    var newPoint = 0
    for (var i = 0; i < newList.length; i++) {
      if (newList[i].selected) {
        newPoint += newList[i].product.minPoint * newList[i].buyCount
      }
    }
    that.setData({
      // newCount: newCount.toFixed(2),
      totalPoint: newPoint,
    })
  },
  goOrderPage : function (e) {
    var that = this;
    var goods = that.data.goods;
    //结算组装json 并且改变所有商品状态
    if (that.data.list.length > 0) {
      that.data.list = []
    }
    for (var i = 0; i < goods.length; i++) {
      var selected = goods[i].selected;
      console.info(goods[i].selected);
      if (selected == true) {
        var json = '{"productId" :' + goods[i].product.productId + ',"title":"' + goods[i].product.title + '","thumbnailImage":"' + goods[i].product.thumbnailImage + '","num":' + goods[i].buyCount + ',"price":' + goods[i].product.minPrice + ',"point":' + goods[i].product.point + ',"lipinkatype":' + goods[i].product.type + ',"inventoryQuantity":' + goods[i].product.inventoryQuantity +',"specPriceId":' + goods[i].specPriceId +  ' }'; 
        that.data.list.push(JSON.parse(json));
        that.setData({
          list:that.data.list,
          lipintype: that.data.list[0].lipinkatype
        })
      }
    }
    if (that.data.list.length > 1) {
      for (var i = 0; i < that.data.list.length; i++) {
        if (that.data.lipintype != that.data.list[i].lipinkatype) {
          wx.showToast({
            title: '不能同时选择两种类型的商品',
            icon: "none"
          })
          return false;
        }
      }
    }
    console.info(that.data.addrId);
    if (that.data.list.length > 0 && that.data.list[0].lipinkatype == 3) {
      console.info(that.data.list);
      wx.navigateTo({
        url: '../confirmOrder/confirmOrder?type=6&index=0&pAndNList=' + JSON.stringify(this.data.list) + '&lipinka=' + that.data.list[0].lipinkatype +'&shoppingCart=true'
      })
    } else if (that.data.list.length > 0 && that.data.list[0].lipinkatype != 3){
      wx.navigateTo({
        url: '../confirmOrder/confirmOrder?type=1&index=0&pAndNList=' + JSON.stringify(this.data.list) + '&shoppingCart=true'
      })
    } else {
      wx.showToast({
        title: '您还没有选择宝贝哦',
        icon: "none"
      })
    }
    
  },
  delOrder: function (e) {
    var that = this;
    var that = this;
    var goods = that.data.goods;
    //结算组装json 并且改变所有商品状态
    if (that.data.list.length > 0) {
      that.data.list = []
    }
    for (var i = 0; i < goods.length; i++) {
      var selected = goods[i].selected;
      if (selected == true) {
        var json =   goods[i].cartId ;
        that.data.list.push(JSON.parse(json));
      }

    }
    if (that.data.list.length > 0) { 
      console.info(JSON.stringify(that.data.list));
      var cartId = JSON.stringify(that.data.list);
      wx.showModal({
        title: '提示',
        content: '确定要删除吗？',
        success: function (res) {
          if (res.confirm) {
            wx.request({
              url: app.globalData.url + "userDeleteShoppingCart",
              header: {
                "content-type": "application/x-www-form-urlencoded"
              },
              data: {
                userId: wx.getStorageSync("userId"),
                cartIds: cartId,
              },
              method: "POST",
              success: function (res) {
               that.onLoad();
              }
            });
            that.selectAll();
          }
        }
      })
    } else {
      wx.showToast({
        title: '您还没有选择宝贝哦',
        icon: "none"
      })
    }
    
    

  },
  goProductDetail:function(e) {
    var that = this;
    if (e.currentTarget.dataset.valid==true) {
      if (e.currentTarget.dataset.lipintype == 2) {
        wx.navigateTo({
          url: '../productDetail/productDetail?productid=' + e.currentTarget.dataset.id + "&discount=" + e.currentTarget.dataset.discount + "&type=2&product=" + JSON.stringify(this.data.goods[e.currentTarget.dataset.index].app) ,
        })
      } else if (e.currentTarget.dataset.lipintype == 1) {
        wx.navigateTo({
          url: '../productDetail/productDetail?productid=' + e.currentTarget.dataset.id + "&type=1" 
          //+ '&lipinka=' + e.currentTarget.dataset.lipintype,
        })
      }else if (e.currentTarget.dataset.lipintype == 3) {
        wx.navigateTo({
          url: '../productDetail/productDetail?productid=' + e.currentTarget.dataset.id + "&product=" + JSON.stringify(this.data.goods[e.currentTarget.dataset.index].product) + '&lipinka=' + e.currentTarget.dataset.lipintype,
        })
      } else {
        wx.navigateTo({
          url: '../productDetail/productDetail?productid=' + e.currentTarget.dataset.id + "&product=" + JSON.stringify(this.data.goods[e.currentTarget.dataset.index].product) ,
        })
      }
    } else {
      wx.showToast({
        title: '商品已下架',
        icon: "none"
      })
    }
  },

  stopClick: function(){
    
  },

  navBack: function () {
    wx.navigateBack({
    })
  },
  editor:function(e){
    var that = this;
    var edit = e.currentTarget.dataset.edit
    if (edit==1) {
        that.setData({
          del:1,
          ed:2
        })
    }
    if (edit == 2) {
      that.setData({
        del: 0,
        ed: 0
      })
    }
  },
  toDetail:function(){
    wx.reLaunch({
      url: '/pages/mallPage/mallPage',
    })
  },
  details: function (res) {
    var productid = res.currentTarget.dataset.productid;
    var type = res.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/productDetail/productDetail?productid=' + productid + '&type=' + type,
    })
  },
})

